(function($, owner) {
	/**
	 * 用户登录
	 **/
	//	var includejs = function(js) {
	//		var scriptTag = document.createElement("script");
	//		scriptTag.setAttribute("type", "text/javascript");
	//		scriptTag.setAttribute("src", "./js/" + js);
	//		document.body.appendChild(scriptTag);
	//	}
	//	includejs("aes_key_iv.js");
	var NetSvrerr = '网络不通或者服务器出错';
	var smsurl = 'http://192.168.1.248:81/SMS';
	var apiurl = 'http://192.168.1.248:81/API';
	var AesKey = 'intelson68280274';
	var AesIV = 'songxg13967161977';
	$.ajaxSetup({
		type: 'post',
		dataType: 'json',
		timeout: 5000,
	});
	var ApiSettings = {
		"MoudleIndex": 100,
		"ScriptIndex": 118001,
		"Action": 902,
		"ActionStep": 1,
		Params: {}
	};

	owner.isdebug = true;

	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		if(!PhoneMobile(loginInfo.account)) {
			return callback('输入的手机号码不正确');
		}
		if(loginInfo.password.length < 6) {
			return callback('密码最短为 6 个字符');
		}
		var p = loginInfo.password;
		loginInfo.password = "\"" + owner.AESencode(p) + "\""; //此处折腾我4小时，不加引号会出现jQuery堆栈溢出的错误。没有引号就不是字符，js认为是对象。
		owner.innerlogin(loginInfo).done(function(data) {
			var logstate = {};
			logstate.account = data[0].phonenum;
			logstate.password = data[0].pass;
			return owner.createState(logstate, callback);
		}).fail(function(err) {
			return callback(err);
		});
	};
	owner.innerlogin = function(userinfo) {
		var quote1 = userinfo.password.substring(0, 1);
		var quote2 = userinfo.password.substring(userinfo.password.substring(userinfo.password.length - 1), 1);
		if(quote1 == '\"' && quote2 == '\"') {
			var pass = userinfo.password;
			userinfo.password = pass.substring(1, pass.length - 1);
		}
		var dfd = new $.Deferred();
		var apidata = {
			"ActionStep": 5,
			Params: {
				"@mm_phonenum": userinfo.account || '',
				"@mm_pass": userinfo.password || '',
			}
		};
		apidata = $.extend(true, ApiSettings, apidata);
		owner.apicall(apidata).done(function(data) {
			if(!$.isEmptyObject(data) && $.isArray(data)) {
				dfd.resolve(data);
			} else {
				dfd.reject('登录失败，用户名或者密码错误');
			}
		}).fail(function(err) {
			dfd.reject(err);
		});
		return dfd.promise();
	}
	owner.AESencode = function(word) {
		srcs = CryptoJS.enc.Utf8.parse(word);
		var encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Utf8.parse(AesKey), {
			iv: CryptoJS.enc.Utf8.parse(AesIV),
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		return encrypted.ciphertext.toString(); //.toUpperCase();
	}
	owner.AESdecode = function(str) {
		var encryptedHexStr = CryptoJS.enc.Hex.parse(str);
		var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
		var decrypt = CryptoJS.AES.decrypt(srcs, CryptoJS.enc.Utf8.parse(AesKey), {
			iv: CryptoJS.enc.Utf8.parse(AesIV),
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
		return decryptedStr.toString();
	}
	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo) {
		var dfd = new $.Deferred();
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if(regInfo.account.length !== 11) {
			return dfd.reject('帐户名需要 11 个数字字符');

		}
		if(regInfo.password.length < 6) {
			return dfd.reject('密码最短需要 6 个字符');

		}
		var qpass = regInfo.password;
		var apidata = {
			"Action": 903,
			"ActionStep": 3,
			Params: {
				"@mm_phonenum": regInfo.account,
				"@mm_name": regInfo.name,
				"@mm_pass": qpass.substring(1, qpass.length - 1),
				"@mm_ps_no": regInfo.psno
			}
		};
		apidata = $.extend(true, ApiSettings, apidata);
		owner.apicall(apidata).done(function(data) {
			//			var newusers = [];
			if(data.error == 0) {
				dfd.resolve();
			} else {
				dfd.reject(data.error);
			}

		}).fail(function(err) {
			dfd.reject(err);

		})
		return dfd.promise();
	};
	owner.createState = function(loginfo, callback) {
		callback = callback || $.noop();
		var state = owner.getState();
		state.account = loginfo.account;
		state.password = loginfo.password;
		owner.setState(state);
		return callback();
	};

	var checkEmail = function(email) {
		email = email || '';
		return(email.length > 3 && email.indexOf('@') > -1);
	};

	//手机号验证
	var PhoneMobile = function(phonenum) {
		phonenum = phonenum || '';
		return phonenum.match(/^(13[0-9]|14(5|7)|15(0|1|2|3|5|6|7|8|9)|18[0-9])\d{8}$/)
	};
	var
		Twitter = {
			checkuser: function(phone) { //检查用户是否已经注册
				var dfd = $.Deferred();

				var apidata = {
					Params: {
						"@mm_phonenum": phone
					}
				};
				apidata = $.extend(true, ApiSettings, apidata);
				owner.apicall(apidata).fail(function(err) {
					dfd.reject(err);
					// return dfd.reject(err);

				}).done(function(data) {
					dfd.resolve(data);

				});
				return dfd.promise();
			},
			sendSMS: function(vdata) {
				var dfd = $.Deferred();
				$.ajax(smsurl, {
					type: 'post',
					dataType: 'json',
					timeout: 5000,
					data: vdata
				}).fail(function(err) {
					dfd.reject(NetSvrerr)
				}).done(function(data) {
					dfd.resolve(data);
				});
				return dfd.promise();
			}
		}
	owner.getvcode = function(vdata) { //获取短信验证码
		var dfd = $.Deferred();
		if(!PhoneMobile(vdata.phoneNum)) {
			dfd.reject('输入的手机号不正确');
		}
		Twitter.checkuser(vdata.phoneNum).then(function(data) {
			//console.log(JSON.stringify(data));
			if(!$.isEmptyObject(data) && $.isArray(data)) {
				dfd.reject('手机号：' + data[0].phonenum + ' 已经被注册');
			} else
				return Twitter.sendSMS(vdata).done(function(data) {
					//					console.log(data.errorMsg);
					if(data.code == 0) {
						dfd.resolve(data);
					} else {
						dfd.reject(data.errorMsg);
					}
				}).fail(function(data) {
					dfd.reject(data);

				});

		}).fail(function(response) {
			//console.log(JSON.stringify(NetSvrerr));
			dfd.reject(response);
		});
		return dfd.promise();
	};

	owner.apicall = function(ajxdata, aurl) { //console.log(JSON.stringify(ajxdata));
		var dfd = $.Deferred();
		$.ajax({
			url: aurl || apiurl,
			data: JSON.stringify(ajxdata),
		}).done(function(data) {
			dfd.resolve(data);

		}).fail(function(err) {
			dfd.reject(NetSvrerr);

		});
		return dfd.promise();
	}

	owner.CanAgainTimer = function(o, text1, text2, delay, ti) {
		var sleep = delay || 60;
		interval = null;
		ti = ti || 1000;
		if(!interval) {
			o.disabled = "disabled";
			sleep--;
			if(text2) {
				o.innerHTML = "(" + sleep + ")" + text2;;
			}
			interval = setInterval(function() {
				if(sleep == 0) {
					if(!!interval) {
						clearInterval(interval);
						interval = null;
						sleep = delay;
						o.removeAttribute('disabled');
						if(text1) {
							o.innerHTML = text1;
						}
					}
					return;
				}
				sleep--;
				if(text2) {
					o.innerHTML = "(" + sleep + ")" + text2;
				}
			}, ti);
		}
	};
	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(phonenum, callback) {
		callback = callback || $.noop;
		if(!PhoneMobile(phonenum)) {
			return callback('输入的手机号码格式不正确');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$speedstate') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$speedstate', JSON.stringify(state));
	};
	/**
	 * 设置应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$speedsettings', JSON.stringify(settings));
	}

	/**
	 * 获取应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$speedsettings') || "{}";
		return JSON.parse(settingsText);
	}
	/**
	 * 获取本地是否安装客户端
	 **/
	owner.isInstalled = function(id) {
		if(id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch(e) {}
		} else {
			switch(id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
}(jQuery, window.app = {}));